//“链表的倒数第k个节点”

//给你一个链表，但不知道链表的长度，如何找到链表中倒数第k个节点？



function findKthFromEnd(head, k){
        let p1 = head;
        let p2 = head;
        //把p2指针移动到正数第n个结点
        for(let i=1; i<k; i++){
            p2 = p2.next;
            if(p2 == null){
                throw new Error("参数n超出链表长度！");
            }
        }
        //p1和p2一起右移，直到p2指向链表尾结点
        while (p2.next != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
}


//链表节点
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 //快速创建链表
 function buildLinkList(array){
    let  head = new Node(array[0]);
    let p = head;
    for(let i=1; i<array.length; i++){
        p.next = new Node(array[i]);
        p = p.next;
    }
    return head;
}



let inputs = [5,3,7,2,4,1,9,8];
let head = buildLinkList(inputs);
let node = findKthFromEnd(head,3);
console.log("链表倒数第3个元素是：" + node.data);
